<template>
    <div>
        <!-- 面包屑导航 -->
        <!-- 搜索筛选 -->
        <el-form :inline="true" class="user-search">
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="selectSlideshow()">查询</el-button>
            </el-form-item>
            <el-form-item label="">
                <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
            </el-form-item>
        </el-form>

        <!--列表-->
        <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border
            element-loading-text="拼命加载中" style="width: 100%;">

            <el-table-column align="center" type="index" width="60" label="序号">
            </el-table-column>

            <el-table-column prop="title" label="标题" width="240">
            </el-table-column>

            <el-table-column prop="indexDetailId" label="栏目页详情分类名称" width="300">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary">{{ typeName(scope.row.indexDetailId) }}</el-button>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" min-width="300">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger"
                        @click="deleteSlideshow(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->

        <!-- 编辑界面 -->
        <el-dialog :title="title" :visible.sync="editFormVisible" width="50%" @click="closeDialog">
            <el-form label-width="120px">
                <el-form-item label="标题">
                    <el-input size="small" v-model="formData.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="栏目页类型">
                    <el-select :multiple="false" v-model="formData.indexDetailId" placeholder="请选择栏目页类型">
                        <el-option v-for="item in indexClassifyLst" :key="item.name" :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="富文本内容" style="height: 400px;">
                    <quill-editor v-model="formData.text" :options="editorOption" style="height: 300px;"
                        ref="QuillEditor">
                    </quill-editor>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialog">取消</el-button>
                <el-button size="small" type="primary" :loading="loading" class="title" @click="addSlideshow()"
                    v-if="title == '添加'">添加</el-button>
                <el-button size="small" type="primary" :loading="loading" class="title" @click="upSlideshow()"
                    v-if="title == '修改'">修改</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择图片" :visible.sync="uploadVisible" width="50%">
            <div>
                <div class="upload-demo">
                    <el-upload action="" :http-request="mainImgUpload" :show-file-list="false" list-type="picture-card">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <!-- <img v-if="formData.mainImg" :src="formData.mainImg" class="avatar"> -->
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {

    selectInformationByIndexIdAndTypes,deleteInformationByIds,
    selectInformationByIndexIdAndIndexDetailIdAndTypes, addInformations, selectIndexDetailByIndexIds,updateInformations
} from "../../api/userMG";
import Pagination from "../../components/Pagination";
import client from "@/utils/ossClient.js";
import VueQuillEditor from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
// 工具栏配置
const toolbarOptions = [
    ["bold", "italic", "underline", "strike"], // toggled buttons
    ["blockquote", "code-block"],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: "ordered" }, { list: "bullet" }],
    [{ script: "sub" }, { script: "super" }], // superscript/subscript
    [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
    [{ direction: "rtl" }], // text direction

    [{ size: ["small", false, "large", "huge"] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
    ["link", "image", "video"], // 对于图片上传这是重点
    ["clean"], // remove formatting button
];
export default {
    data() {
        return {
            uploadVisible: false,
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions, // 工具栏
                        handlers: {
                            image: (value) => {
                                if (value) {
                                    // 在这里编写图片按钮点击操作
                                    this.uploadVisible = true;
                                    this.cursorIndex =
                                        this.$refs.QuillEditor.quill.getSelection().index;
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },
            loading: false, //是显示加载
            editFormVisible: false, //控制编辑页面显示与隐藏
            title: "添加",
            listData: [],
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 20,
                total: 10,
            },
            formData: {
                title: "",//标题
                indexId: '',//栏目页id
                text: '',//富文本内容
                indexDetailId: '',
                type: '3',
            },
            columnPageItem: {},
            indexClassifyLst: [],//栏目页分类

        }
    },
    // 注册组件
    components: {
        Pagination,
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */
    created() {
        this.selectSlideshow()
        this.selectIndexDetailByIndexIdsList()
    },
    computed: {
        typeName() {
            return typeId => {
                let name = ''
                this.indexClassifyLst.forEach(item => {
                    if (item.id == typeId) {
                        name = item.name

                    }
                })
                return name
            }
        }
    },
    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
        selectIndexDetailByIndexIdsList() {
            let columnPageItem = JSON.parse(localStorage.getItem('columnPageItem'))
            selectIndexDetailByIndexIds({
                indexId: columnPageItem.id
            }).then((res) => {
                if (res.code == 200) {
                    this.indexClassifyLst = res.data.data;
                    return;
                }

            });
        },
        mainImgUpload(file) {
            var self = this;
            //判断扩展名
            const tmpcnt = file.file.name.lastIndexOf(".");
            const exname = file.file.name.substring(tmpcnt + 1);
            const names = ["jpg", "jpeg", "webp", "png", "bmp"];
            // if (names.indexOf(exname) < 0) {
            //   this.$message.error("不支持的格式!");
            //   return;
            // }
            const fileName = file.file.uid + "." + exname;
            client
                .put(fileName, file.file)
                .then((res) => {
                    if (res.url) {
                        console.log('res.url=======', res.url)
                        self.getUrl(res.url);
                    } else {
                        this.$message.error("文件上传失败");
                    }
                })
                .catch((err) => { });
        },

        getUrl(url) {

            this.uploadVisible = false;
            // 获取富文本组件实例
            let quill = this.$refs.QuillEditor.quill;
            // 如果上传成功
            if (url) {
                // 插入图片，res为服务器返回的图片链接地址

                quill.insertEmbed(this.cursorIndex, "image", url);
                // 调整光标到最后
                quill.setSelection(this.cursorIndex + 1);
            } else {
                // 提示上传失败信息
            }
        },
        // 删除
        deleteSlideshow(index, row) {
            this.$confirm("确定要删除吗?", "信息", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteInformationByIds({ id: row.id })
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    type: "success",
                                    message: "已删除！",
                                });
                                this.selectSlideshow();
                            } else {
                                this.$message({
                                    type: "info",
                                    message: res.msg,
                                });
                            }
                        })
                        .catch((err) => {
                            this.loading = false;
                            this.$message.error("删除失败，请稍后再试！");
                        });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },

        //修改轮播图
        upSlideshow() {
            this.loading = true;
            var formData = JSON.parse(JSON.stringify(this.formData));
            updateInformations(formData).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.editFormVisible = false
                    this.$message({
                        type: "success",
                        message: res.msg,
                    });
                    this.selectSlideshow();
                } else {
                    this.$message.error(res.msg);
                }
            });
        },

        //添加轮播图
        addSlideshow() {
            this.loading = true;
            var formData = JSON.parse(JSON.stringify(this.formData))
            let columnPageItem = JSON.parse(localStorage.getItem('columnPageItem'))
            this.formData.indexId = columnPageItem.id
            addInformations(this.formData).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.editFormVisible = false
                    this.$message({
                        type: "success",
                        message: res.msg,
                    });
                    this.selectSlideshow();
                } else {
                    this.$message.error(res.msg);
                }
            });
        },
        // 获取轮播图
        selectSlideshow() {
            let columnPageItem = JSON.parse(localStorage.getItem('columnPageItem'))
            this.loading = true;
            selectInformationByIndexIdAndTypes({
                indexId: columnPageItem.id,
                type: 3,
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.listData = res.data.data;
                    return;
                }
                this.$message({
                    type: "info",
                    message: res.msg,
                })
            });
        },
        // 分页插件事件
        callFather(parm) {
            this.getDishesList(parm.currentPage);
        },

        //显示编辑界面
        handleEdit: function (index, row) {
            this.editFormVisible = true;
            if (row != undefined && row != "undefined") {
                this.title = "修改";
                this.formData.id = row.id;
                this.formData.indexId = row.indexId;
                this.formData.title= row.title;
                this.formData.text = row.text;
                this.formData.indexDetailId = row.indexDetailId;

            } else {
                this.title = "添加";
                this.formData.id ='';
                this.formData.indexId ='';
                this.formData.text ='';
                this.formData.title = ''
                this.formData.indexDetailId = ''
            }
        },

        // 关闭编辑、增加弹出框
        closeDialog() {
            this.editFormVisible = false;
        },
    },
};
</script>

<style scoped>
.user-search {
    margin-top: 20px;
}

.userRole {
    width: 100%;
}

.upload-demo {
    display: flex;
    flex-direction: row;
}

.upload-demo img {
    width: 140px;
    height: 140px;
}
</style>